#!/usr/bin/env python
from numpy import *
from racecar.parse import *
from racecar.data import *
from racecar.cluster import *
import getopt
import sys
import os

# Print usage information for this script. 
def usage():
  print "decluster.py [options]";
  print "Options:"
  print "-i /path/to/file : Full path of discrete data file."
  print "--orange /path/to/file : Full path of discrete data file in Orange format.";
  print "-v : Turn on verbose - this displays a lot of junk you probably don't need.";

# Main entry point for the script. 
def main():
  # Get command line arguments. 
  try:
    opts, args = getopt.getopt(sys.argv[1:], "i:v", ["orange="])
  except getopt.GetoptError:
    usage();
    sys.exit(1)
    
  datapath = None;
  parseMethod = None;
  verbose = False;
  for o,a in opts:
    if o == "-i":
      datapath = os.path.realpath(a);
      if os.path.splitext(datapath)[1] == '.tab':
        print "** WARNING: file extension is .tab which implies Orange, "\
        "but you used -i which implies a racecar data format. If you want to "\
        "load Orange data, use --orange.";
        print "";
      parseMethod = parseBayesData;
    
    if o == "--orange":
      datapath = os.path.realpath(a);
      parseMethod = parseOrangeData;
    
    if o == "-v":
      verbose = True;
  
  # If datapath is still none, you didn't pass a data file..
  if datapath == None:
    usage();
    sys.exit(1);
      
  # If the data file isn't valid, choke. 
  if not os.path.isfile(datapath):
    print "Data file cannot be found. Make sure to specify the full path.";
    print "";
    usage();
    sys.exit(1);
  
  # Load 'er up.
  print "Loading data file.."
  data = parseMethod(datapath);

  # Run the clustering. 
  print "Running exact cluster algorithm.."
  cobj = ExactClusterator(data);
  cobj.cluster();
  print "Clustering finished..";
  print "Number of variables originally: " + str(data.numVars());
  print "Number of clusters: " + str(cobj.getNumClusters());
  
  # Print clustering information.
  if verbose:
    print "Cluster information: "
    cobj.printClusters();
  
  # Print the data. 
  print "Writing clustered data to file..";
  filename = os.path.splitext(datapath)[0] + "_clustered" + os.path.splitext(datapath)[1];
  cobj.writeData(filename);
  print "Filename: " + str(filename);
    
if __name__ == "__main__":
  main();
